#include "./linked-list.h"
#include <stdio.h>
#include <stdlib.h>

LinkedList createList(int array[], int length)
{
	LinkedList list = (LNode *)malloc(sizeof(LNode));
	list->data = 0;
	list->next = NULL;
	int i;
	LNode *pointer = list;
	for (i = 0; i < length; i++)
	{
		LNode *node = (LNode *)malloc(sizeof(LNode));
		node->data = array[i];
		node->next = NULL;
		pointer->next = node;
		pointer = pointer->next;
	}
	return list;
}

void listInsert(LinkedList list, int data, int index)
{
	if (list == NULL)
	{
		return;
	}
	// 索引到index的前一个
	LNode *pointer = getListNode(list, index - 1);
	if (pointer == NULL)
	{
		return;
	}
	LNode *node = (LNode *)malloc(sizeof(LNode));
	node->data = data;
	node->next = pointer->next;
	pointer->next = node;
}

void listDelete(LinkedList list, int index)
{
	if (list == NULL)
	{
		return;
	}
	// 索引到index的前一个
	LNode *pointer = getListNode(list, index - 1);
	if (pointer == NULL || pointer->next == NULL)
	{
		return;
	}
	LNode *remove = pointer->next;
	pointer->next = remove->next;
	free(remove);
}

LNode *getListNode(LinkedList list, int index)
{
	// 头结点的下标视为-1
	int i = -1;
	LNode *pointer = list;
	while (pointer != NULL && i < index)
	{
		pointer = pointer->next;
		i++;
	}
	return pointer;
}

void printList(LinkedList list)
{
	LNode *pointer = list;
	printf("O");
	while ((pointer = pointer->next) != NULL)
	{
		printf(" -> %d", pointer->data);
	}
	printf(" -> ^\n");
}